import Mock from 'mockjs'
/** 静态指定mock数据 */
const staticTables = [
    { tableId: 'A01', tableType: '小桌', tableStatus: '空闲' },
    { tableId: 'A02', tableType: '中桌', tableStatus: '空闲' },
    { tableId: 'A03', tableType: '大桌', tableStatus: '空闲' }
  ]

 

// 动态生成扩展数据
// const dynamicTables = Mock.mock({
//     'list|20': [{
//       'tableType|1': ['小桌', '中桌', '大桌'],
//       'tableId': function(){
//         const prefix = {
//         '小桌': 'A','中桌': 'B', '大桌': 'C'
//       }[this.tableType]

//       //生成两位数编号
//       const num = Mock.mock('@natural(1,20)')
//         .toString().padStart(2,'0')
//       return `${prefix}${num}`
//     },
//       'tableStatus|1': ['空闲', '占用']
//     }]
//   })

let mockTables = [...staticTables]

/** 静态指定mock数据 */
const staticDishs = [
    {
        dishId: 1,
        dishName: '菲力牛排',
        dishPrice: 69,
        dishType: '单品',
        category: '主食',
        picture: '',
        dishStatus: '上架',
        tasteOptions: [
          { tasteId: 1, tasteName: '三分熟', tasteType: '熟度' },
          { tasteId: 2, tasteName: '五分熟', tasteType: '熟度' },
          { tasteId: 3, tasteName: '七分熟', tasteType: '熟度' },
          { tasteId: 4, tasteName: '全熟', tasteType: '熟度' }
        ]
    },
    {
        dishId: 2,
        dishName: '柠檬可乐',
        dishPrice: 19,
        dishType: '单品',
        category: '饮料',
        picture: '',
        dishStatus: '上架',
        tasteOptions: [
          { tasteId: 5, tasteName: '正常冰', tasteType: '冰度' },
          { tasteId: 6, tasteName: '少冰', tasteType: '冰度' },
          { tasteId: 7, tasteName: '去冰', tasteType: '冰度' },
          { tasteId: 8, tasteName: '全糖', tasteType: '甜度' },
          { tasteId: 9, tasteName: '半糖', tasteType: '甜度' }
        ]
    },
    {
        dishId: 3,
        dishName: '三文鱼沙拉',
        dishPrice: 39,
        dishType: '套餐',
        category: '前菜',
        picture: '',
        dishStatus: '下架'
    }
  ]

 

// 动态生成扩展数据
// const dynamicDishs = Mock.mock({
//     'list|20': [{
//         'dishId|+1': 1, 
//         dishName: '@ctitle',
//         price: Mock.Random.float(0,2),
//       'type|1': ['单品', '套餐'],
//       'category|1': ['主食', '饮料', '前菜', '甜品'],
//       picture: Mock.Random.image,
//       'status|1': ['上架', '下架']
//     }]
//   })

let mockDishs = [...staticDishs]

/** 静态指定mock数据 */
const staticCategorys = [
    { categoryId: 1, categoryName: '主食' },
    { categoryId: 2, categoryName: '饮料' },
    { categoryId: 3, categoryName: '前菜' },
    { categoryId: 4, categoryName: '甜品' }
  ]

 

// 动态生成扩展数据
// const dynamicCategorys = Mock.mock({
//     'list|20': [{
//         'categoryId|+1': 1, 
//         categoryName: '@ctitle',
//     }]
//   })

let mockCategorys = [...staticCategorys]

/** 静态指定mock数据 */
const staticTastes = [
    { tasteId: 1, tasteName: '三分熟', tasteType: '熟度' },
    { tasteId: 2, tasteName: '五分熟', tasteType: '熟度' },
    { tasteId: 3, tasteName: '七分熟', tasteType: '熟度' },
    { tasteId: 4, tasteName: '全熟', tasteType: '熟度' },
    { tasteId: 5, tasteName: '正常冰', tasteType: '冰度' },
    { tasteId: 6, tasteName: '少冰', tasteType: '冰度' },
    { tasteId: 7, tasteName: '去冰', tasteType: '冰度' },
    { tasteId: 8, tasteName: '全糖', tasteType: '甜度' },
    { tasteId: 9, tasteName: '半糖', tasteType: '甜度' },
  ]

 

// 动态生成扩展数据
// const dynamicTastes = Mock.mock({
//     'list|20': [{
//         'tasteId|+1': 1, 
//         tasteName: '@ctitle',
//     }]
//   })

let mockTastes = [...staticTastes]

/** 静态指定mock数据 */
const staticOrders = [
    { 
      orderId: '2022503101211', 
      table: {
        tableId: 'A01'
      }, 
      peopleCount: 3,
      dishes: [
        {
          dish: {
            dishId: 'D001',
            dishName: '黑椒牛排',
            dishPrice: 78,
            category: '主菜'
          },
          quantity: 1,
          note: '123'
        },
        {
          dish: {
            dishId: 'D001',
            dishName: '黑椒牛排',
            dishPrice: 78,
            category: '主菜'
          },
          quantity: 1,
          note: '123'
        },
      ],
      orderAmount: 156, 
      discountAmount: 10,
      receivedAmount: 146, 
      orderTime: '20250316', 
      payTime: '20250316', 
      orderStatus: '已支付', 
      paymentMethod: '微信',
      remarks: '要黑椒酱'
    },
    { 
      orderId: '2022503101212', 
      table: {
        tableId: 'A02'
      }, 
      peopleCount: 4,
      dishes: [
        {
          dish: {
            dishId: 'D001',
            dishName: '黑椒牛排',
            dishPrice: 78,
            category: '主菜'
          },
          quantity: 1,
          note: '123'
        },
        {
          dish: {
            dishId: 'D001',
            dishName: '黑椒牛排',
            dishPrice: 78,
            category: '主菜'
          },
          quantity: 1,
          note: '123'
        },
      ],
      orderAmount: 156, 
      discountAmount: 10,
      receivedAmount: 146, 
      orderTime: '20250316', 
      payTime: '20250316', 
      orderStatus: '待支付', 
      paymentMethod: '支付宝',
      remarks: '要番茄酱'
    },
    { 
      orderId: '2022503101213', 
      table: {
        tableId: 'A03'
      }, 
      peopleCount: 5,
      dishes: [
        {
          dish: {
            dishId: 'D001',
            dishName: '黑椒牛排',
            dishPrice: 78,
            category: '主菜'
          },
          quantity: 1,
          note: '123'
        },
        {
          dish: {
            dishId: 'D001',
            dishName: '黑椒牛排',
            dishPrice: 78,
            category: '主菜'
          },
          quantity: 1,
          note: '123'
        },
      ],
      orderAmount: 156, 
      discountAmount: 10,
      receivedAmount: 146, 
      orderTime: '20250316', 
      payTime: '20250316', 
      orderStatus: '已取消',
      paymentMethod: '现金',
      remarks: '不要酱'
    }
  ]

let mockOrders = [...staticOrders]

const staticTickets = [
  { 
    ticketId: 'T001', 
    ticketName: '【超值】招牌双人牛排套餐', 
    value: 129, 
    packageId: '1', 
    packageName: '招牌双人牛排套餐', 
    packagePrice: 129, 
    validTime: '永久有效', 
    ticketStatus: '1', 
    description: '双人牛排套餐，包含两份牛排、两份汤和一份沙拉',
    createTime: '2025-03-10 12:00:00',
    updateTime: '2025-03-10 12:00:00'
  },
  { 
    ticketId: 'T002', 
    ticketName: '【超值】水果沙拉套餐', 
    value: 19, 
    packageId: '2', 
    packageName: '水果沙拉套餐', 
    packagePrice: 19, 
    validTime: '30天', 
    ticketStatus: '1', 
    description: '健康沙拉套餐，包含多种新鲜蔬菜',
    createTime: '2025-03-10 12:00:00',
    updateTime: '2025-03-10 12:00:00'
  }
]

let mockTickets = [...staticTickets]

const staticTasks = [
  {
    taskId: 'T202503101211',
    orderId: '2022503101211',
    tableId: 'A01',
    dishes: [
      {
        dish: {
          dishId: 'D001',
          dishName: '黑椒牛排',
          dishPrice: 78,
          category: '主菜'
        },
        quantity: 1,
        status: '待制作',
        remark: '五分熟，黑椒汁分开',
        startTime: null,
        finishTime: null
      },
      {
        dish: {
          dishId: 'D002',
          dishName: '奶油蘑菇汤',
          dishPrice: 28,
          category: '汤品'
        },
        quantity: 1,
        status: '待制作',
        remark: '多加奶油',
        startTime: null,
        finishTime: null
      }
    ],
    taskStatus: '待处理',
    createTime: '2025-03-10 12:11:00',
    updateTime: null
  },
  {
    taskId: 'T202503101212',
    orderId: '2022503101212',
    tableId: 'A02',
    dishes: [
      {
        dish: {
          dishId: 'D003',
          dishName: '菲力牛排',
          dishPrice: 98,
          category: '主菜'
        },
        quantity: 1,
        status: '制作中',
        remark: '全熟，配黑椒汁',
        startTime: '2025-03-10 12:15:30',
        finishTime: null
      },
      {
        dish: {
          dishId: 'D004',
          dishName: '凯撒沙拉',
          dishPrice: 38,
          category: '前菜'
        },
        quantity: 1,
        status: '已完成',
        remark: '不要面包丁',
        startTime: '2025-03-10 12:16:00',
        finishTime: '2025-03-10 12:20:00'
      }
    ],
    taskStatus: '处理中',
    createTime: '2025-03-10 12:12:30',
    updateTime: '2025-03-10 12:20:00'
  },
  {
    taskId: 'T202503101213',
    orderId: '2022503101213',
    tableId: 'A03',
    dishes: [
      {
        dish: {
          dishId: 'D005',
          dishName: '意大利面',
          dishPrice: 48,
          category: '主食'
        },
        quantity: 1,
        status: '已完成',
        remark: '不要蒜',
        startTime: '2025-03-10 12:10:00',
        finishTime: '2025-03-10 12:18:00'
      },
      {
        dish: {
          dishId: 'D006',
          dishName: '提拉米苏',
          dishPrice: 38,
          category: '甜品'
        },
        quantity: 1,
        status: '已完成',
        remark: '',
        startTime: '2025-03-10 12:18:30',
        finishTime: '2025-03-10 12:22:00'
      }
    ],
    taskStatus: '已完成',
    createTime: '2025-03-10 12:10:00',
    updateTime: '2025-03-10 12:22:00'
  }
]

let mockTasks = [...staticTasks]

// 模拟月度数据
const staticMonthlySales = [
  { timeLabel: '1月', timeValue: 1, amount: 120, orderCount: 15 },
  { timeLabel: '2月', timeValue: 2, amount: 150, orderCount: 18 },
  { timeLabel: '3月', timeValue: 3, amount: 230, orderCount: 25 },
  { timeLabel: '4月', timeValue: 4, amount: 150, orderCount: 20 },
  { timeLabel: '5月', timeValue: 5, amount: 120, orderCount: 15 },
  { timeLabel: '6月', timeValue: 6, amount: 200, orderCount: 22 },
  { timeLabel: '7月', timeValue: 7, amount: 230, orderCount: 25 },
  { timeLabel: '8月', timeValue: 8, amount: 200, orderCount: 22 },
  { timeLabel: '9月', timeValue: 9, amount: 100, orderCount: 12 },
  { timeLabel: '10月', timeValue: 10, amount: 180, orderCount: 20 },
  { timeLabel: '11月', timeValue: 11, amount: 150, orderCount: 18 },
  { timeLabel: '12月', timeValue: 12, amount: 120, orderCount: 15 }
]

// 模拟年度数据
const staticYearlySales = [
  { timeLabel: '2022年', timeValue: 2022, amount: 1850, orderCount: 120 },
  { timeLabel: '2023年', timeValue: 2023, amount: 2100, orderCount: 150 },
  { timeLabel: '2024年', timeValue: 2024, amount: 2450, orderCount: 180 }
]

// 模拟分类数据
const staticCategorySales = [
  { categoryId: 1, categoryName: '前菜', amount: 100, percentage: 15, orderCount: 20 },
  { categoryId: 2, categoryName: '主食', amount: 186, percentage: 28, orderCount: 35 },
  { categoryId: 3, categoryName: '小吃', amount: 173, percentage: 26, orderCount: 30 },
  { categoryId: 4, categoryName: '甜品', amount: 150, percentage: 22, orderCount: 25 },
  { categoryId: 5, categoryName: '饮料', amount: 222, percentage: 33, orderCount: 40 }
]

let mockMonthlySales = [...staticMonthlySales]
let mockYearlySales = [...staticYearlySales]
let mockCategorySales = [...staticCategorySales]

/** 配置Mock接口 */
/** 特别注意与api/table.ts路径接口名、后端接口保持一致*/
export default [
   //查询所有
  {
    url: '/dev-api/table/listAll', 
    method: 'get',
    response: () => ({
      code: 200, msg: '查询成功', data: mockTables 
    })
  },

  //条件查询
  {
    url:  '/dev-api/table',
    method: 'get',
    response: ({ query }) => {
        const filtered = mockTables.filter(t => {
            const idMatch = t.tableId.includes(query.tableId || '')
            const statusMatch = query.tableStatus ? t.tableStatus === query.tableStatus : true
            return idMatch && statusMatch
          })
          return { code: 200, data: filtered, msg: 'success' }
    }
  },

  //分页查询
  {
    url:  '/dev-api/table/page',
    method: 'get',
    response: ({ query }) => {
        const pageNum = parseInt(query.pageNum) || 1
        const pageSize = parseInt(query.pageSize) || 10
        
        const filtered = mockTables.filter(t => {
          const idMatch = t.tableId.includes(query.tableId || '')
          const statusMatch = query.tableStatus ? t.tableStatus === query.tableStatus : true
          return idMatch && statusMatch
        })
        
        const paged = filtered.slice((pageNum - 1) * pageSize, pageNum * pageSize)
        return {
            code: 200,
            data: {
              list: paged,
              total: filtered.length,
              pageNum,
              pageSize
            },
            msg: 'success'
          }
    }
  },

  //按id查询
  {
    url:  '/dev-api/table/:tableId',
    method: 'get',
    response: ({ url }) => {
        const tableId = url.split('/').pop()
      const table = mockTables.find(t => t.tableId === tableId)
      return table 
        ? { code: 200, data: table, msg: 'success' }
        : { code: 404, msg: '餐台不存在' }
    }
  },

  //按状态查询
  {
    url:  '/dev-api/table/getByStatus/:status',
    method: 'get',
    response: ({ url }) => {
        const status = url.split('/').pop()
        const filtered = mockTables.filter(t => t.tableStatus === status)
        return { code: 200, data: filtered, msg: 'success' }
    }
  },

  //新增
  {
    url:  '/dev-api/table',
    method: 'post',
    response: ({ body }) => {
        const newTable = { 
            ...body,
            // tableId: Mock.mock('@guid')
          }
          mockTables.push(newTable)
          return { code: 200, data: newTable, msg: '新增成功' }
    }
  },

  //修改
  {
    url:  '/dev-api/table',
    method: 'put',
    response: ({ body }) => {
        const index = mockTables.findIndex(t => t.tableId === body.tableId)
      if (index === -1) {
        return { code: 404, msg: '餐台不存在' }
      }
      mockTables[index] = { ...mockTables[index], ...body }
      return { code: 200, data: mockTables[index], msg: '更新成功' }
    }
  },

  //删除
  {
    url:  '/dev-api/table/:tableId',
    method: 'delete',
    response: ({ url }) => {
        const tableId = url.split('/').pop()
        const initialLength = mockTables.length
        console.log('删除前:', mockTables)
        mockTables = mockTables.filter(t => t.tableId !== tableId)
        console.log('删除后:', mockTables)
        return initialLength === mockTables.length
          ? { code: 404, msg: '删除失败，餐台不存在' }
          : { code: 200, msg: '删除成功' }
    }
  },

  //批量删除
  {
    url:  '/dev-api/table/delBatch/:tableIds',
    method: 'delete',
    response: ({ url }) => {
        const tableIds = url.split('/').pop().split(',')
      const initialLength = mockTables.length
      mockTables = mockTables.filter(t => !tableIds.includes(t.tableId))
      return {
        code: 200,
        data: initialLength - mockTables.length,
        msg: `成功删除${initialLength - mockTables.length}条数据`
      }
    }
  },

  //查询所有
  {
    url: '/dev-api/dish/listAll', 
    method: 'get',
    response: () => ({
      code: 200, msg: '查询成功', data: mockDishs 
    })
  },

  //条件查询
  {
    url:  '/dev-api/dish',
    method: 'get',
    response: ({ query }) => {
        const filtered = mockDishs.filter(d => {
            const nameMatch = d.dishName.includes(query.dishName || '')
            const categoryMatch = query.category ? d.category === query.category : true
            return nameMatch && categoryMatch
          })
          return { code: 200, data: filtered, msg: 'success' }
    }
  },

  //分页查询
  {
    url:  '/dev-api/dish/page',
    method: 'get',
    response: ({ query }) => {
        const pageNum = parseInt(query.pageNum) || 1
        const pageSize = parseInt(query.pageSize) || 10
        
        const filtered = mockDishs.filter(d => {
          const nameMatch = d.dishName.includes(query.dishName || '')
          const categoryMatch = query.category ? d.category === query.category : true
          return nameMatch && categoryMatch
        })
        
        const paged = filtered.slice((pageNum - 1) * pageSize, pageNum * pageSize)
        return {
            code: 200,
            data: {
              list: paged,
              total: filtered.length,
              pageNum,
              pageSize
            },
            msg: 'success'
          }
    }
  },

  //按id查询
  {
    url:  '/dev-api/dish/:dishId',
    method: 'get',
    response: ({ url }) => {
        const dishId = Number(url.split('/').pop())
      const dish = mockDishs.find(d => d.dishId === dishId)
      return dish
        ? { code: 200, data: dish, msg: 'success' }
        : { code: 404, msg: '菜品不存在' }
    }
  },

  //按dishName查询
  {
    url:  '/dev-api/dish/:dishName',
    method: 'get',
    response: ({ url }) => {
        const dishName = url.split('/').pop()
      const dish = mockDishs.find(d => d.dishName === dishName)
      return dish
        ? { code: 200, data: dish, msg: 'success' }
        : { code: 404, msg: '菜品不存在' }
    }
  },

  //按分类查询
  {
    url:  '/dev-api/dish/getByCategory/:category',
    method: 'get',
    response: ({ url }) => {
        const category = url.split('/').pop()
        const filtered = mockDishs.filter(d => d.category === category)
        return { code: 200, data: filtered, msg: 'success' }
    }
  },

  //新增
  {
    url:  '/dev-api/dish',
    method: 'post',
    response: ({ body }) => {
      // 计算下一个ID（确保静态数据初始ID正确）
  const nextId = mockDishs.length > 0 
  ? Math.max(...mockDishs.map(d => d.dishId)) + 1 
  : 1;
        const newDish = { 
            ...body,
            dishId: nextId, // 直接赋值数字ID
          }
          mockDishs.push(newDish)
          return { code: 200, data: newDish, msg: '新增成功' }
    }
  },

  //修改
  {
    url:  '/dev-api/dish',
    method: 'put',
    response: ({ body }) => {
        const index = mockDishs.findIndex(d => d.dishId === body.dishId)
      if (index === -1) {
        return { code: 404, msg: '菜品不存在' }
      }
      mockDishs[index] = { ...mockDishs[index], ...body }
      return { code: 200, data: mockDishs[index], msg: '更新成功' }
    }
  },

  //删除
  {
    url:  '/dev-api/dish/:dishId',
    method: 'delete',
    response: ({ url }) => {
        const dishId = Number(url.split('/').pop())
        const initialLength = mockDishs.length
        mockDishs = mockDishs.filter(d => d.dishId !== dishId)
        return initialLength === mockDishs.length
          ? { code: 404, msg: '删除失败，菜品不存在' }
          : { code: 200, msg: '删除成功' }
    }
  },

  //批量删除
  {
    url:  '/dev-api/dish/delBatch/:dishIds',
    method: 'delete',
    response: ({ url }) => {
        const dishIds = url.split('/').pop().split(',').map(id => Number(id));
      const initialLength = mockDishs.length
      mockDishs = mockDishs.filter(d => !dishIds.includes(d.dishId))
      return {
        code: 200,
        data: initialLength - mockDishs.length,
        msg: `成功删除${initialLength - mockDishs.length}条数据`
      }
    }
  },

   //查询所有
   {
    url: '/dev-api/category/listAll', 
    method: 'get',
    response: () => ({
      code: 200, msg: '查询成功', data: mockCategorys 
    })
  },

  //条件查询
  {
    url:  '/dev-api/category',
    method: 'get',
    response: ({ query }) => {
        const filtered = mockCategorys.filter(c => {
            const nameMatch = c.categoryName.includes(query.categoryName || '')
            return nameMatch
          })
          return { code: 200, data: filtered, msg: 'success' }
    }
  },

  //分页查询
  {
    url:  '/dev-api/category/page',
    method: 'get',
    response: ({ query }) => {
        const pageNum = parseInt(query.pageNum) || 1
        const pageSize = parseInt(query.pageSize) || 10
        
        const filtered = mockCategorys.filter(c => {
          const nameMatch = c.categoryName.includes(query.categoryName || '')
          return nameMatch
        })
        
        const paged = filtered.slice((pageNum - 1) * pageSize, pageNum * pageSize)
        return {
            code: 200,
            data: {
              list: paged,
              total: filtered.length,
              pageNum,
              pageSize
            },
            msg: 'success'
          }
    }
  },

  //按id查询
  {
    url:  '/dev-api/category/:categoryId',
    method: 'get',
    response: ({ url }) => {
        const categoryId = Number(url.split('/').pop())
      const category = mockCategorys.find(c => c.categoryId === categoryId)
      return category
        ? { code: 200, data: category, msg: 'success' }
        : { code: 404, msg: '分类不存在' }
    }
  },

  //按categoryName查询
  {
    url:  '/dev-api/category/:categoryName',
    method: 'get',
    response: ({ url }) => {
        const categoryName = url.split('/').pop()
      const category = mockCategorys.find(c => c.categoryName === categoryName)
      return category
        ? { code: 200, data: category, msg: 'success' }
        : { code: 404, msg: '分类不存在' }
    }
  },

  //新增
  {
    url:  '/dev-api/category',
    method: 'post',
    response: ({ body }) => {
      // 计算下一个ID（确保静态数据初始ID正确）
  const nextId = mockCategorys.length > 0 
  ? Math.max(...mockCategorys.map(c => c.categoryId)) + 1 
  : 1;
        const newCategory = { 
            ...body,
            categoryId: nextId, // 直接赋值数字ID
          }
          mockCategorys.push(newCategory)
          return { code: 200, data: newCategory, msg: '新增成功' }
    }
  },

  //修改
  {
    url:  '/dev-api/category',
    method: 'put',
    response: ({ body }) => {
        const index = mockCategorys.findIndex(c => c.categoryId === body.categoryId)
      if (index === -1) {
        return { code: 404, msg: '分类不存在' }
      }
      mockCategorys[index] = { ...mockCategorys[index], ...body }
      return { code: 200, data: mockCategorys[index], msg: '更新成功' }
    }
  },

  //删除
  {
    url:  '/dev-api/category/:categoryId',
    method: 'delete',
    response: ({ url }) => {
        const categoryId = Number(url.split('/').pop())
        const initialLength = mockCategorys.length
        mockCategorys = mockCategorys.filter(c => c.categoryId !== categoryId)
        return initialLength === mockCategorys.length
          ? { code: 404, msg: '删除失败，分类不存在' }
          : { code: 200, msg: '删除成功' }
    }
  },

  //批量删除
  {
    url:  '/dev-api/category/delBatch/:categoryIds',
    method: 'delete',
    response: ({ url }) => {
        const categoryIds = url.split('/').pop().split(',').map(id => Number(id));
      const initialLength = mockCategorys.length
      mockCategorys = mockCategorys.filter(c => !categoryIds.includes(c.categoryId))
      return {
        code: 200,
        data: initialLength - mockCategorys.length,
        msg: `成功删除${initialLength - mockCategorys.length}条数据`
      }
    }
  },

   //查询所有
   {
    url: '/dev-api/taste/listAll', 
    method: 'get',
    response: () => ({
      code: 200, msg: '查询成功', data: mockTastes 
    })
  },

  //条件查询
  {
    url:  '/dev-api/taste',
    method: 'get',
    response: ({ query }) => {
        const filtered = mockTastes.filter(t => {
            const nameMatch = t.tasteName.includes(query.tasteName || '')
            return nameMatch
          })
          return { code: 200, data: filtered, msg: 'success' }
    }
  },

  //分页查询
  {
    url:  '/dev-api/taste/page',
    method: 'get',
    response: ({ query }) => {
        const pageNum = parseInt(query.pageNum) || 1
        const pageSize = parseInt(query.pageSize) || 10
        
        const filtered = mockTastes.filter(t => {
          const nameMatch = t.tasteName.includes(query.tasteName || '')
          return nameMatch
        })
        
        const paged = filtered.slice((pageNum - 1) * pageSize, pageNum * pageSize)
        return {
            code: 200,
            data: {
              list: paged,
              total: filtered.length,
              pageNum,
              pageSize
            },
            msg: 'success'
          }
    }
  },

  //按id查询
  {
    url:  '/dev-api/taste/:tasteId',
    method: 'get',
    response: ({ url }) => {
        const tasteId = Number(url.split('/').pop())
      const taste = mockTastes.find(t => t.tasteId === tasteId)
      return taste
        ? { code: 200, data: taste, msg: 'success' }
        : { code: 404, msg: '口味不存在' }
    }
  },

  //按tasteName查询
  {
    url:  '/dev-api/taste/:tasteName',
    method: 'get',
    response: ({ url }) => {
        const tasteName = url.split('/').pop()
      const taste = mockTastes.find(t => t.tasteName === tasteName)
      return taste
        ? { code: 200, data: taste, msg: 'success' }
        : { code: 404, msg: '口味不存在' }
    }
  },

  //新增
  {
    url:  '/dev-api/taste',
    method: 'post',
    response: ({ body }) => {
      const tasteType = body.tasteType || '其他'
      // 计算下一个ID（确保静态数据初始ID正确）
  const nextId = mockTastes.length > 0 
  ? Math.max(...mockTastes.map(t => t.tasteId)) + 1 
  : 1;
        const newTaste = { 
            // ...body,
            tasteId: nextId, // 直接赋值数字ID
            tasteName: body.tasteName,
      tasteType: tasteType
          }
          mockTastes.push(newTaste)
          return { code: 200, data: newTaste, msg: '新增成功' }
    }
  },

  //修改
  {
    url:  '/dev-api/taste',
    method: 'put',
    response: ({ body }) => {
        const index = mockTastes.findIndex(t => t.tasteId === body.tasteId)
      if (index === -1) {
        return { code: 404, msg: '口味不存在' }
      }
      mockTastes[index] = { ...mockTastes[index], ...body }
      return { code: 200, data: mockTastes[index], msg: '更新成功' }
    }
  },

  //删除
  {
    url:  '/dev-api/taste/:tasteId',
    method: 'delete',
    response: ({ url }) => {
        const tasteId = Number(url.split('/').pop())
        const initialLength = mockTastes.length
        mockTastes = mockTastes.filter(t => t.tasteId !== tasteId)
        return initialLength === mockTastes.length
          ? { code: 404, msg: '删除失败，口味不存在' }
          : { code: 200, msg: '删除成功' }
    }
  },

  //批量删除
  {
    url:  '/dev-api/taste/delBatch/:tasteIds',
    method: 'delete',
    response: ({ url }) => {
        const tasteIds = url.split('/').pop().split(',').map(id => Number(id));
      const initialLength = mockTastes.length
      mockTastes = mockTastes.filter(t => !tasteIds.includes(t.tasteId))
      return {
        code: 200,
        data: initialLength - mockTastes.length,
        msg: `成功删除${initialLength - mockTastes.length}条数据`
      }
    }
  },

   //查询所有
    {
      url: '/dev-api/order/listAll', 
      method: 'get',
      response: () => ({
        code: 200, msg: '查询成功', data: mockOrders 
      })
    },
  
    //条件查询
    {
      url:  '/dev-api/order',
      method: 'get',
      response: ({ query }) => {
          const filtered = mockOrders.filter(o => {
              const idMatch = o.orderId.includes(query.orderId || '')
              const statusMatch = query.orderStatus ? o.orderStatus === query.orderStatus : true
              return idMatch && statusMatch
            })
            return { code: 200, data: filtered, msg: 'success' }
      }
    },
  
    //分页查询
    {
      url:  '/dev-api/order/page',
      method: 'get',
      response: ({ query }) => {
          const pageNum = parseInt(query.pageNum) || 1
          const pageSize = parseInt(query.pageSize) || 10
          
          const filtered = mockOrders.filter(o => {
            const idMatch = o.orderId.includes(query.orderId || '')
            const statusMatch = query.orderStatus ? o.orderStatus === query.orderStatus : true
            return idMatch && statusMatch
          })
          
          const paged = filtered.slice((pageNum - 1) * pageSize, pageNum * pageSize)
          return {
              code: 200,
              data: {
                list: paged,
                total: filtered.length,
                pageNum,
                pageSize
              },
              msg: 'success'
            }
      }
    },
  
    //按id查询
    {
      url:  '/dev-api/order/:orderId',
      method: 'get',
      response: ({ url }) => {
          const orderId = url.split('/').pop()
        const order = mockOrders.find(o => o.orderId === orderId)
        return order 
          ? { code: 200, data: order, msg: 'success' }
          : { code: 404, msg: '订单不存在' }
      }
    },
  
    //按状态查询
    {
      url:  '/dev-api/order/getByStatus/:status',
      method: 'get',
      response: ({ url }) => {
          const status = url.split('/').pop()
          const filtered = mockOrders.filter(o => o.orderStatus === status)
          return { code: 200, data: filtered, msg: 'success' }
      }
    },

    //按桌台id查询
    {
      url:  '/dev-api/order/getByTable/:tableId',
      method: 'get',
      response: ({ query }) => {
        // const order = mockOrders.find(o => 
        //   o.table?.tableId &&
        //   o.table?.tableId.toString() === params.tableId && 
        //   ['待点菜', '待结账'].includes(o.orderStatus)
        // )
        // return order 
        //   ? { code: 200, data: order, msg: 'success' } 
        //   : { code: 404, msg: `桌台 ${params.tableId} 无有效订单` }
        const filtered = mockOrders.filter(o => {
          const idMatch = o.orderId.includes(query.orderId || '')
          const statusMatch = query.orderStatus ? o.orderStatus === query.orderStatus : true
          // 新增tableId过滤条件
          const tableMatch = query.tableId ? o.table.tableId === query.tableId : true
          return idMatch && statusMatch && tableMatch
        })

            // 新增排序逻辑：按订单时间倒序排列
    const sorted = filtered.sort((a, b) => 
      new Date(b.orderTime).getTime() - new Date(a.orderTime).getTime()
    )
        return { code: 200, data: sorted[0] || null, msg: 'success' } // 返回第一个匹配项
      }
    },
  
    //新增
    {
      url:  '/dev-api/order',
      method: 'post',
      response: ({ body }) => {
          const newOrder = { 
              ...body,
              orderId: Mock.mock('@guid'),
              orderAmount: 0,
              discountAmount: 0,
              receivedAmount: 0,
              payTime: null,
              paymentMethod: null,
              remarks: ''
            }
            mockOrders.push(newOrder)
            return { code: 200, data: newOrder, msg: '新增成功' }
      }
    },
  
    //修改
    {
      url:  '/dev-api/order',
      method: 'put',
      response: ({ body }) => {
          const index = mockOrders.findIndex(o => o.orderId === body.orderId)
        if (index === -1) {
          return { code: 404, msg: '订单不存在' }
        }
        mockOrders[index] = { ...mockOrders[index], ...body }
        return { code: 200, data: mockOrders[index], msg: '更新成功' }
      }
    },
  
    //删除
    {
      url:  '/dev-api/order/:orderId',
      method: 'delete',
      response: ({ url }) => {
          const orderId = url.split('/').pop()
          const initialLength = mockOrders.length
          mockOrders = mockOrders.filter(o => o.orderId !== orderId)
          return initialLength === mockOrders.length
            ? { code: 404, msg: '删除失败，订单不存在' }
            : { code: 200, msg: '删除成功' }
      }
    },
  
    //批量删除
    {
      url:  '/dev-api/order/delBatch/:orderIds',
      method: 'delete',
      response: ({ url }) => {
          const orderIds = url.split('/').pop().split(',')
        const initialLength = mockOrders.length
        mockOrders = mockOrders.filter(o => !orderIds.includes(o.orderId))
        return {
          code: 200,
          data: initialLength - mockOrders.length,
          msg: `成功删除${initialLength - mockOrders.length}条数据`
        }
      }
    },
    
    // 开台点餐
    {
      url: '/dev-api/order/makeNewOrder',
      method: 'post',
      response: ({ body }) => {
      // 生成唯一订单ID（格式兼容现有数据）
      const orderId = `${new Date().toISOString().replace(/[^0-9]/g, '').slice(0, 14)}${Math.floor(Math.random()*900+100)}`
      // 获取原桌台信息（假设 mockTables 是预定义的桌台列表）
      const originalTable = mockTables.find(t => t.tableId === body.table.tableId);
      // 创建新订单
      const newOrder = {
        orderId: `${orderId}`,
        table: { 
            tableId: body.table.tableId,
            tableType: originalTable?.tableType,
            tableStatus: '待点菜'
        },
        peopleCount: body.peopleCount || 1,
        dishes: [],
        orderAmount: 0,
        discountAmount: 0,
        receivedAmount: 0,
        orderTime: new Date().toISOString(),
        payTime: '',
        orderStatus: '待支付',
        paymentMethod: '',
        remarks: ''
      }
  
      // 更新桌台状态
    const tableIndex = mockTables.findIndex(t => t.tableId === body.table.tableId);
    if (tableIndex !== -1) {
      mockTables[tableIndex].tableStatus = '待点菜';
    }
    
      // 更新数据
      // mockOrders.push(newOrder)
      mockOrders.unshift(newOrder) //添加到数组开头
      console.log('当前所有订单:', mockOrders); // 调试
      return { 
        code: 200, 
        data: newOrder,
        msg: '开台成功'
      }
      }
    },
  
    // 录入点餐菜品明细，也可以发起post请求
    {
      url: '/order/enterItem/:orderId/items',
      method: 'post',
      response: ({ url, body }) => {
        const orderId = url.split('/').pop()
        const order = mockOrders.find(o => o.orderId === orderId)
        if (!order) {
          return { code: 404, msg: '订单不存在' }
        }
        const newItem = {
          dish: body.dish,
          quantity: body.quantity,
          note: body.note || ''
        }
        // 计算总金额
        order.dishes.push(newItem)
        order.orderAmount = order.dishes.reduce((sum, item) => 
          sum + (item.dish.dishPrice * item.quantity), 0)
        
        return { code: 200, data: order, msg: '添加菜品成功' }
      }
    },
    
    // 结束录入菜品
    {
      url: '/order/endOrder',
      method: 'get',
      response: ({  }) => {
      }
    },
    
    // 确认支付，也可以发起post请求
    {
      url: '/order/:orderId/makePayment',
      method: 'post',
      response: ({ url, body }) => {
        const orderId = url.split('/').pop()
        const order = mockOrders.find(o => o.orderId === orderId)
        
        if (!order) return { code: 404, msg: '订单不存在' }
        if (order.orderStatus !== '已下单') {
          return { code: 400, msg: '订单状态不正确' }
        }
  
        // 计算实收金额
        order.discountAmount = body.discountAmount || 0
        order.receivedAmount = order.orderAmount - order.discountAmount
        order.paymentMethod = body.paymentMethod
        order.payTime = new Date().toISOString()
        order.orderStatus = '已支付'
  
        // 释放桌台（需要与桌台Mock数据联动）
        const table = mockTables.find(t => t.tableId === order.table.tableId)
        if (table) {
          table.tableStatus = '空闲'
        }
  
        return { code: 200, data: order, msg: '支付成功' }
      }
    },
    
    // 修改一行菜品明细数量
    {
      url: '/order/changeQuantity/:orderId/items/:itemIndex',
      method: 'put',
      response: ({ url, body }) => {
        const [orderId, itemIndex] = url.split('/').slice(-3, -1)
        const order = mockOrders.find(o => o.orderId === orderId)
        
        if (!order) return { code: 404, msg: '订单不存在' }
        if (isNaN(itemIndex) || itemIndex >= order.dishes.length) {
          return { code: 400, msg: '无效的菜品项' }
        }
        order.dishes[itemIndex] = {
          ...order.dishes[itemIndex],
          quantity: body.quantity,
          note: body.note || ''
        }
        // 重新计算总金额
        order.orderAmount = order.dishes.reduce((sum, item) => 
          sum + (item.dish.dishPrice * item.quantity), 0)
        
        return { code: 200, data: order, msg: '修改成功' }
      }
    },
    
    // 删除一行菜品明细
    {
      url: '/order/deleteItem/:orderId/items/:itemIndex',
      method: 'delete',
      response: ({ url }) => {
        const [orderId, itemIndex] = url.split('/').slice(-3, -1)
        const order = mockOrders.find(o => o.orderId === orderId)
        
        if (!order) return { code: 404, msg: '订单不存在' }
        if (isNaN(itemIndex) || itemIndex >= order.dishes.length) {
          return { code: 400, msg: '无效的菜品项' }
        }
  
        order.dishes.splice(itemIndex, 1)
  
        // 重新计算总金额
        order.orderAmount = order.dishes.reduce((sum, item) => 
          sum + (item.dish.dishPrice * item.quantity), 0)
        
        return { code: 200, data: order, msg: '删除成功' }
  
      }
    },

// 查询所有
{
  url: '/dev-api/ticket/listAll',
  method: 'get',
  response: () => ({
    code: 200, msg: '查询成功', data: mockTickets
  })
},

// 条件查询
{
  url: '/dev-api/ticket',
  method: 'get',
  response: ({ query }) => {
    const filtered = mockTickets.filter(t => {
      const nameMatch = t.ticketName.includes(query.ticketName || '')
      const valueMatch = query.value ? t.value === Number(query.value) : true
      const statusMatch = query.ticketStatus ? t.ticketStatus === query.ticketStatus : true
      return nameMatch && valueMatch && statusMatch
    })
    return { code: 200, data: filtered, msg: 'success' }
  }
},

// 分页查询
{
  url: '/dev-api/ticket/page',
  method: 'get',
  response: ({ query }) => {
    const pageNum = parseInt(query.pageNum) || 1
    const pageSize = parseInt(query.pageSize) || 10

    const filtered = mockTickets.filter(t => {
      const nameMatch = t.ticketName.includes(query.ticketName || '')
      const valueMatch = query.value ? t.value === Number(query.value) : true
      const statusMatch = query.ticketStatus ? t.ticketStatus === query.ticketStatus : true
      return nameMatch && valueMatch && statusMatch
    })

    const paged = filtered.slice((pageNum - 1) * pageSize, pageNum * pageSize)
    return {
      code: 200,
      data: {
        list: paged,
        total: filtered.length,
        pageNum,
        pageSize
      },
      msg: 'success'
    }
  }
},

// 按id查询
{
  url: '/dev-api/ticket/:ticketId',
  method: 'get',
  response: ({ url }) => {
    const ticketId = url.split('/').pop()
    const ticket = mockTickets.find(t => t.ticketId === ticketId)
    return ticket
      ? { code: 200, data: ticket, msg: 'success' }
      : { code: 404, msg: '团购券不存在' }
  }
},

// 新增
{
  url: '/dev-api/ticket',
  method: 'post',
  response: ({ body }) => {
    const newTicket = {
      ...body,
      ticketId: 'T' + Mock.mock('@natural(100,999)'),
      createTime: Mock.mock('@datetime'),
      updateTime: Mock.mock('@datetime')
    }
    mockTickets.push(newTicket)
    return { code: 200, data: newTicket, msg: '新增成功' }
  }
},

// 修改
{
  url: '/dev-api/ticket',
  method: 'put',
  response: ({ body }) => {
    const index = mockTickets.findIndex(t => t.ticketId === body.ticketId)
    if (index === -1) {
      return { code: 404, msg: '团购券不存在' }
    }
    mockTickets[index] = { 
      ...mockTickets[index], 
      ...body,
      updateTime: Mock.mock('@datetime')
    }
    return { code: 200, data: mockTickets[index], msg: '更新成功' }
  }
},

// 删除
{
  url: '/dev-api/ticket/:ticketId',
  method: 'delete',
  response: ({ url }) => {
    const ticketId = url.split('/').pop()
    const initialLength = mockTickets.length
    mockTickets = mockTickets.filter(t => t.ticketId !== ticketId)
    return initialLength === mockTickets.length
      ? { code: 404, msg: '删除失败，团购券不存在' }
      : { code: 200, msg: '删除成功' }
  }
},

// 批量删除
{
  url: '/dev-api/ticket/delBatch/:ticketIds',
  method: 'delete',
  response: ({ url }) => {
    const ticketIds = url.split('/').pop().split(',')
    const initialLength = mockTickets.length
    mockTickets = mockTickets.filter(t => !ticketIds.includes(t.ticketId))
    return {
      code: 200,
      data: initialLength - mockTickets.length,
      msg: `成功删除${initialLength - mockTickets.length}条数据`
    }
  }
},

    {
      url: '/dev-api/dashboard/data',
      method: 'get',
      response: ({ query }: { query: any }) => {
        const { timeType } = query
        
        const responseData = {
          monthlySales: timeType === 'year' ? [] : mockMonthlySales,
          yearlySales: timeType === 'year' ? mockYearlySales : [],
          categorySales: mockCategorySales,
          statsPeriod: '2024-08-01 至 2024-08-08',
          totalAmount: mockCategorySales.reduce((sum, item) => sum + item.amount, 0),
          totalOrderCount: mockCategorySales.reduce((sum, item) => sum + item.orderCount, 0)
        }
  
        return {
          code: 200,
          msg: '获取仪表盘数据成功',
          data: responseData
        }
      }
    },

    // 获取所有厨房任务
  {
    url: '/dev-api/kitchen/tasks',
    method: 'get',
    response: () => {
      return {
        code: 200,
        message: 'success',
        data: mockTasks
      }
    }
  },
  
  // 更新菜品状态
  {
    url: '/dev-api/kitchen/tasks/dish-status',
    method: 'put',
    response: ({ body }) => {
      const { taskId, dishId, status } = body
      const task = mockTasks.find(t => t.taskId === taskId)
      
      if (task) {
        const dish = task.dishes.find(d => d.dish.dishId === dishId)
        if (dish) {
          dish.status = status
          
          // 更新开始或完成时间
          if (status === '制作中') {
            dish.startTime = new Date().toISOString()
          } else if (status === '已完成') {
            dish.finishTime = new Date().toISOString()
          }
          
          // 更新任务状态
          if (task.dishes.every(d => d.status === '已完成')) {
            task.taskStatus = '已完成'
          } else if (task.dishes.some(d => d.status === '制作中')) {
            task.taskStatus = '处理中'
          } else {
            task.taskStatus = '待处理'
          }
          task.updateTime = new Date().toISOString()
          
          return {
            code: 200,
            message: '菜品状态更新成功',
            data: task
          }
        }
      }
      
      return {
        code: 404,
        message: '未找到对应任务或菜品',
        data: null
      }
    }
  },
  
  // 完成整个任务
  {
    url: '/dev-api/kitchen/tasks/complete',
    method: 'put',
    response: ({ body }) => {
      const { taskId } = body
      console.log('收到完成任务请求,taskId:', taskId) // 调试日志
      const taskIndex = mockTasks.findIndex(t => t.taskId === taskId)
      
      if (taskIndex !== -1) {
        const task = mockTasks[taskIndex]
        
        // 确保所有菜品都已完成
        if (task.dishes.every(d => d.status === '已完成')) {
          task.taskStatus = '已完成'
          task.updateTime = new Date().toISOString()
          
          // 从列表中移除已完成任务
          mockTasks.splice(taskIndex, 1)
          
          return {
            code: 200,
            message: '任务完成成功',
            data: task
          }
        } else {
          return {
            code: 400,
            message: '还有菜品未完成，不能完成任务',
            data: null
          }
        }
      }
      
      return {
        code: 404,
        message: '未找到对应任务',
        data: null
      }
    }
  },

  // 创建厨房任务API
{
  url: '/dev-api/order/createKitchenTask',
  method: 'post',
  response: ({ body }) => {
    const { orderId } = body
    const order = mockOrders.find(o => o.orderId === orderId)
    
    if (!order) {
      console.error('缺失的订单ID:', orderId);
      console.error('现有订单:', mockOrders.map(o => o.orderId));
      return { code: 404, msg: '订单不存在', data: null }
    }
    
    // 生成任务ID
    const taskId = `T${orderId.slice(-6)}`
    
    // 创建厨房任务
    const newTask = {
      taskId,
      orderId: order.orderId,
      tableId: order.table.tableId,
      dishes: order.dishes.map(dish => ({
        dish: dish.dish,
        quantity: dish.quantity,
        status: '待制作',
        remark: dish.note || '',
        startTime: null,
        finishTime: null
      })),
      taskStatus: '待处理',
      createTime: new Date().toISOString(),
      updateTime: null
    }
    
    // 添加到任务列表
    mockTasks.push(newTask)
    
    // 更新订单状态
    order.orderStatus = '待支付'
    
 // 更新桌台状态为"用餐中"
 const table = mockTables.find(t => t.tableId === order.table.tableId)
 if (table) {
   table.tableStatus = '用餐中'
 }

    return {
      code: 200,
      data: newTask,
      msg: '厨房任务创建成功'
    }
  }
},
]

